package com.ccjk.beusoft.hot.plugin

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.AssetManager
import android.content.res.Resources
import android.os.Bundle
import android.widget.Toast
import com.ccjk.beusoft.plugin.host.Util
import java.lang.Exception

/**
 * Created by CCJK on 2017/12/2.
 */
class ActivityProxy(private val proxyActivity: Activity) {

    private lateinit var pluginPackage: PluginPackage
    private lateinit var pluginActivityName: String
    private lateinit var activityInfo: ActivityInfo
    private lateinit var pluginActivity: PluginActivityInterface

    fun onCreate(intent: Intent) {
        val pluginPackageName = intent.getStringExtra(Const.KEY_PLUGIN_PACKAGE_NAME)
        val tempPackage = PluginManager.getPluginPackage(pluginPackageName)
        if (tempPackage == null) {
            Toast.makeText(proxyActivity, "插件包不存在", Toast.LENGTH_SHORT).show()
            return
        }
        pluginPackage = tempPackage
        val tempActivityName = intent.getStringExtra(Const.KEY_PLUGIN_ACTIVITY_NAME)
        pluginActivityName = tempActivityName ?: pluginPackage.defaultActivityClassName
        var tempActivityInfo: ActivityInfo? = null
        pluginPackage.packageInfo.activities?.let {
            tempActivityInfo = it.filter {
                pluginActivityName == it.name
            }.getOrNull(0)
        }
        if (tempActivityInfo == null) {
            Toast.makeText(proxyActivity, "插件不存在該類", Toast.LENGTH_SHORT).show()
            return
        }
        activityInfo = tempActivityInfo!!


//        startActivity()
        Util.startActivity(proxyActivity, pluginPackage, pluginActivityName)

    }

    private fun startActivity() {
        try {
            val pluginActivityClass = pluginPackage.pluginClassLoader.loadClass(pluginActivityName)
            val constructor = pluginActivityClass.getConstructor()
            pluginActivity = constructor.newInstance() as PluginActivityInterface
            //將proxyActivity 綁定到插件的activity中
            pluginActivity.bind(proxyActivity, pluginPackage)
            //將pluginActivity 綁定到代理的activity中
            (proxyActivity as Bind).bind(pluginActivity as Activity, pluginPackage)

            //
            val bundle = Bundle()
            bundle.putInt(Const.KEY_ACTIVITY_FROM, Const.FROM_EXTERNAL)
            pluginActivity.onCreate(bundle)
        } catch (e: Exception) {
            Toast.makeText(proxyActivity, "啓動失敗", Toast.LENGTH_SHORT).show()
        }
    }

    fun getPluginClassLoader(): ClassLoader = pluginPackage.pluginClassLoader
    fun getPluginAssetManager(): AssetManager? = pluginPackage.assetManager
    fun getPluginResource(): Resources? = pluginPackage.resources


}